package com.edu.study.base.stuAnswerResultSummary.service.impl;

import com.edu.study.base.StuAnswerResultDetail.domain.StuAnswerResultDetail;
import com.edu.study.base.StuAnswerResultDetail.service.IStuAnswerResultDetailService;
import com.edu.study.base.StuAnswerResultErrorDetail.domain.StuAnswerResultErrorDetail;
import com.edu.study.base.StuAnswerResultErrorDetail.service.IStuAnswerResultErrorDetailService;
import com.edu.study.base.StuQuestionPaper.service.IStuQuestionPaperService;
import com.edu.study.base.questionKind.domain.StuQuestionKind;
import com.edu.study.base.questionKind.service.IStuQuestionKindService;
import com.edu.study.base.stuAnswerResultSummary.domain.AnswerResult;
import com.edu.study.base.stuAnswerResultSummary.domain.AnswerResultSummaryEntity;
import com.edu.study.base.stuAnswerResultSummary.domain.StuAnswerResultSummary;
import com.edu.study.base.stuAnswerResultSummary.mapper.StuAnswerResultSummaryMapper;
import com.edu.study.base.stuAnswerResultSummary.service.IStuAnswerResultSummaryService;
import com.edu.study.base.stuQuestionCatalog.domain.StuQuestionCatalog;
import com.edu.study.base.stuQuestionCatalog.service.IStuQuestionCatalogService;
import com.edu.study.base.stuQuestionLibrary.domain.StuQuestionLibraryRy;
import com.edu.study.base.stuQuestionLibrary.service.IStuQuestionLibraryRyService;
import com.edu.study.base.stuQuestionOption.domain.StuQuestionOption;
import com.edu.study.base.stuQuestionOption.service.IStuQuestionOptionService;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 答题结果汇总Service业务层处理
 * 
 * @author jjt
 * @date 2021-06-20
 */
@Service
//@DataSource(value = DataSourceType.SLAVE)
@Transactional
public class StuAnswerResultSummaryServiceImpl implements IStuAnswerResultSummaryService 
{
    @Autowired
    private StuAnswerResultSummaryMapper stuAnswerResultSummaryMapper;

    @Autowired
    private IStuQuestionLibraryRyService questionLibraryRyService;

    @Autowired
    private IStuQuestionKindService stuQuestionKindService;

    @Autowired
    private IStuQuestionOptionService stuQuestionOptionService;

    @Autowired
    private IStuAnswerResultSummaryService answerResultSummaryService;

    @Autowired
    private IStuAnswerResultErrorDetailService answerResultErrorDetailService;

    @Autowired
    private IStuAnswerResultDetailService answerResultDetailService;

    @Autowired
    private IStuQuestionCatalogService questionCatalogService;

    @Autowired
    private IStuQuestionPaperService questionPaperService;

    @Autowired
    private RedisCache redisCache;
    /**
     * 查询答题结果汇总
     * 
     * @param id 答题结果汇总ID
     * @return 答题结果汇总
     */
    @Override
    public StuAnswerResultSummary selectStuAnswerResultSummaryById(Long id)
    {
        return stuAnswerResultSummaryMapper.selectStuAnswerResultSummaryById(id);
    }

    /**
     * 查询答题结果汇总列表
     * 
     * @param stuAnswerResultSummary 答题结果汇总
     * @return 答题结果汇总
     */
    @Override
    public List<StuAnswerResultSummary> selectStuAnswerResultSummaryList(StuAnswerResultSummary stuAnswerResultSummary)
    {
        return stuAnswerResultSummaryMapper.selectStuAnswerResultSummaryList(stuAnswerResultSummary);
    }

    /**
     * 新增答题结果汇总
     * 
     * @param stuAnswerResultSummary 答题结果汇总
     * @return 结果
     */
    @Override
    public int insertStuAnswerResultSummary(StuAnswerResultSummary stuAnswerResultSummary)
    {
        return stuAnswerResultSummaryMapper.insertStuAnswerResultSummary(stuAnswerResultSummary);
    }

    /**
     * 修改答题结果汇总
     * 
     * @param stuAnswerResultSummary 答题结果汇总
     * @return 结果
     */
    @Override
    public int updateStuAnswerResultSummary(StuAnswerResultSummary stuAnswerResultSummary)
    {
        return stuAnswerResultSummaryMapper.updateStuAnswerResultSummary(stuAnswerResultSummary);
    }

    /**
     * 批量删除答题结果汇总
     * 
     * @param ids 需要删除的答题结果汇总ID
     * @return 结果
     */
    @Override
    public int deleteStuAnswerResultSummaryByIds(Long[] ids)
    {
        return stuAnswerResultSummaryMapper.deleteStuAnswerResultSummaryByIds(ids);
    }

    /**
     * 删除答题结果汇总信息
     * 
     * @param id 答题结果汇总ID
     * @return 结果
     */
    @Override
    public int deleteStuAnswerResultSummaryById(Long id)
    {
        return stuAnswerResultSummaryMapper.deleteStuAnswerResultSummaryById(id);
    }

    /**
     * 提交能力测试结果
     * @param answerResult
     * @return
     */
    @Override
    public AjaxResult batchSubmitResult(AnswerResult answerResult){

        if(answerResult != null && answerResult.getQuestionPaperId() == null){
            return AjaxResult.error("题卷id为空");
        }
        Map result = new HashMap();
        if (answerResult != null && answerResult.getEntityList() != null && answerResult.getEntityList().size() > 0) {
            Long questionPaperId = answerResult.getQuestionPaperId();//题卷id
            //从redis中获取题下的所有的题，如果没有则在mysql中搜索
            List<StuQuestionLibraryRy> libraryRyList = redisCache.getCacheList("librarys_" + questionPaperId);
            if(libraryRyList !=  null && libraryRyList.size() > 0){
            }else{
                //根据题卷id获取题卷下面所有的题
                libraryRyList = questionLibraryRyService.getAppLibraryByPaperId(questionPaperId);
                if(libraryRyList != null && libraryRyList.size() > 0){
                    redisCache.setCacheList("librarys_" + questionPaperId,libraryRyList);
                    redisCache.expire("librarys_" + questionPaperId,1, TimeUnit.DAYS);
                }
            }
            //获得所有的题型，根据题型设定的分数来计算得分
            List<StuQuestionKind> stuQuestionKinds = redisCache.getCacheList("questionKinds_" + questionPaperId);
            if(stuQuestionKinds != null && stuQuestionKinds.size()>0){
            }else{
                List<Long> questionTypeIds = libraryRyList.stream().map(StuQuestionLibraryRy::getQuestionTypeId).distinct().collect(Collectors.toList());
                stuQuestionKinds = stuQuestionKindService.selectStuQuestionKindListByIds(questionTypeIds);
                if(stuQuestionKinds != null && stuQuestionKinds.size() > 0){
                    redisCache.setCacheList("questionKinds_" + questionPaperId,libraryRyList);
                    redisCache.expire("questionKinds_" + questionPaperId,1, TimeUnit.DAYS);
                }
            }
            Map<Long, StuQuestionLibraryRy> libraryRyMap = libraryRyList.stream().collect(Collectors.toMap(StuQuestionLibraryRy::getId, e -> e));
            Map<Long, StuQuestionKind> kindsMap = stuQuestionKinds.stream().collect(Collectors.toMap(StuQuestionKind::getId, e -> e));
//
            //循环答题结果计算分数
            List<AnswerResultSummaryEntity> entityList = answerResult.getEntityList();
            if (entityList != null && entityList.size() > 0) {
                List<StuQuestionCatalog> catalogList  =  redisCache.getCacheList("questionCatalogsList_score_"+questionPaperId);
                if (catalogList != null && catalogList.size() > 0) {
                }else{
                    List<Long> catalogIds = entityList.stream().map(AnswerResultSummaryEntity::getCatalogId).distinct().collect(Collectors.toList());
                    catalogList  = questionCatalogService.selectByCatalogIds(catalogIds);
                    redisCache.setCacheList("questionCatalogsList_score_"+questionPaperId,catalogList);
                }
                if (catalogList != null && catalogList.size() > 0) {
                    Map<Long, StuQuestionCatalog> catalogMap = catalogList.stream().collect(Collectors.toMap(StuQuestionCatalog::getId, e -> e));
                    List<StuAnswerResultErrorDetail> errorDetailList = new ArrayList<>();
                    List<StuAnswerResultDetail> detailList = new ArrayList<>();
                    BigDecimal total = new BigDecimal(0);
                    for (AnswerResultSummaryEntity entity : entityList) {
                        String answerValue = entity.getAnswerValue();//用户所选答案
                        StuQuestionLibraryRy libraryRy = libraryRyMap.get(entity.getLibraryId());
                        List<StuQuestionOption> optionList = libraryRy.getOptionList();
                        if(optionList != null && optionList.size() > 0){
                            StuQuestionCatalog catalog = catalogMap.get(entity.getCatalogId());
                            BigDecimal scoreRightValue = catalog.getScoreRightValue();
                            BigDecimal scoreWrongValue = catalog.getScoreWrongValue();
                            BigDecimal scoreNoValue = catalog.getScoreNoValue();
                            scoreRightValue = scoreRightValue == null?new BigDecimal(0):scoreRightValue;
                            scoreWrongValue = scoreWrongValue == null?new BigDecimal(0):scoreWrongValue;
                            StuQuestionKind stuQuestionKind = kindsMap.get(libraryRy.getQuestionTypeId());
                            if(stuQuestionKind != null && stuQuestionKind.getIsMoreSelect() == 0 ){//判断是否是多选
                                boolean flag = false;
                                boolean giveUp = true;
                                for (StuQuestionOption option : optionList) {
                                    if(option.getOptionContent().equals(answerValue)){
                                        //进来说明没有放弃答题
                                        giveUp = false;
                                        if("1".equals(option.getIsAnswer()) ){
                                            //回答正确
                                            flag  = true;
                                            break;
                                        }
                                    }
                                }
                                if(!giveUp){//没有放弃
                                    if( !flag){
                                        total = total.subtract(scoreWrongValue);
                                        StuAnswerResultErrorDetail errorDetail = new StuAnswerResultErrorDetail();
                                        errorDetail.setAppUserId(SecurityUtils.getUserId());
                                        errorDetail.setQuestionLibraryId(libraryRy.getId());
                                        errorDetail.setAnswerErrorContent(answerValue);
                                        errorDetail.setScoreValue(scoreWrongValue);
                                        errorDetail.setCreateDate(new Date());
                                        errorDetail.setUpdateDate(new Date());
                                        errorDetail.setCreateUserId(SecurityUtils.getUserId());
                                        errorDetailList.add(errorDetail);
                                    }else{
                                        total = total.add(scoreRightValue);
                                        StuAnswerResultDetail detail = new StuAnswerResultDetail();
                                        detail.setAppUserId(SecurityUtils.getUserId());
                                        detail.setQuestionLibraryId(libraryRy.getId());
                                        detail.setAnswerContent(answerValue);
                                        detail.setScoreValue(scoreRightValue);
                                        detail.setCreateDate(new Date());
                                        detail.setUpdateDate(new Date());
                                        detail.setCreateUserId(SecurityUtils.getUserId());
                                        detailList.add(detail);
                                    }
                                }else{
                                    //放弃答题
                                    total = total.add(scoreNoValue);
                                    StuAnswerResultErrorDetail errorDetail = new StuAnswerResultErrorDetail();
                                    errorDetail.setAppUserId(SecurityUtils.getUserId());
                                    errorDetail.setQuestionLibraryId(libraryRy.getId());
                                    errorDetail.setAnswerErrorContent(answerValue);
                                    errorDetail.setScoreValue(scoreNoValue);
                                    errorDetail.setCreateDate(new Date());
                                    errorDetail.setUpdateDate(new Date());
                                    errorDetail.setCreateUserId(SecurityUtils.getUserId());
                                    errorDetailList.add(errorDetail);
                                }

                            }

                        }
                    }

                    StuAnswerResultSummary summary = new StuAnswerResultSummary();
                    summary.setAppUserId(SecurityUtils.getUserId());
                    summary.setRelationId(questionPaperId);//题卷id
                    summary.setType(2);
                    summary.setScoreValue(total);
                    summary.setDeleteFlag("0");
                    summary.setAnswerStartTime(answerResult.getStartTime());
                    summary.setAnswerEndTime(answerResult.getEndTime());
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(answerResult.getStartTime());
                    long startMillis = calendar.getTimeInMillis();
                    calendar.setTime(answerResult.getEndTime());
                    long endMilis = calendar.getTimeInMillis();
                    long duration = (endMilis - startMillis)/1000;
                    summary.setTotalDuration(duration);
                    if(answerResult.getEntityList().size() == libraryRyList.size()){
                        summary.setIsAllOver("1");//全部答完
                    }else{
                        summary.setIsAllOver("0");
                    }
                    int i = answerResultSummaryService.insertStuAnswerResultSummary(summary);
                    if(i > 0){
                        errorDetailList.forEach(e -> {
                            e.setStudentAnswerResultId(summary.getId());
                            answerResultErrorDetailService.insertStuAnswerResultErrorDetail(e);
                        });
                        detailList.forEach( e-> {
                            e.setStudentAnswerResultId(summary.getId());
                            answerResultDetailService.insertStuAnswerResultDetail(e);
                        });
                    }
                    result.put("totalScore",total);
                    //TODO 根据得分解锁阶梯

                }
            }

        }
        return AjaxResult.success("提交成功",result);
    }

    @Override
    public AjaxResult submitWrite(AnswerResultSummaryEntity entity) {
        Long libraryId = entity.getLibraryId();
        if(libraryId == null)
            return AjaxResult.error("题目标识为空");
        Long catalogId = entity.getCatalogId();
        StuAnswerResultSummary summary = new StuAnswerResultSummary();
        summary.setAppUserId(SecurityUtils.getUserId());
        summary.setRelationId(catalogId);
        summary.setType(3);
        summary.setDeleteFlag("0");
        summary.setIsAllOver("1");//全部答完
        int i = answerResultSummaryService.insertStuAnswerResultSummary(summary);
        if(i>0){
            StuAnswerResultDetail detail = new StuAnswerResultDetail();
            detail.setAppUserId(SecurityUtils.getUserId());
            detail.setQuestionLibraryId(libraryId);
            detail.setAnswerContent(entity.getAnswerValue());
            detail.setCreateDate(new Date());
            detail.setUpdateDate(new Date());
            detail.setCreateUserId(SecurityUtils.getUserId());
            answerResultDetailService.insertStuAnswerResultDetail(detail);
        }
        if(entity.getIsTeacherCorrect() != null && entity.getIsTeacherCorrect() == 1){
            //TODO 下老师批改作业订单
        }

        return AjaxResult.success();
    }


    @Override
    public AjaxResult submitSingle(AnswerResultSummaryEntity entity) {
        Long libraryId = entity.getLibraryId();
        if(libraryId == null)
            return AjaxResult.error("题目标识为空");
        //根据题目id查询题目
        StuQuestionLibraryRy stuQuestionLibraryRy = questionLibraryRyService.selectStuQuestionLibraryRyInfoById(libraryId);

        if(stuQuestionLibraryRy!=null){
            Long questionTypeId = stuQuestionLibraryRy.getQuestionTypeId();
            StuQuestionKind stuQuestionKind = stuQuestionKindService.selectStuQuestionKindById(questionTypeId);//获得题型
            //获得选项答案
            StuQuestionOption option = new StuQuestionOption();
            option.setQuestionLibraryId(libraryId);
            List<StuQuestionOption> stuQuestionOptions = stuQuestionOptionService.selectStuQuestionOptionList(option);
            if(stuQuestionOptions != null && stuQuestionOptions.size()>0){
                boolean flag = false;
                for (StuQuestionOption stuQuestionOption : stuQuestionOptions) {
                    if(stuQuestionOption.getOptionContent().equals(entity.getAnswerValue())){
                        flag = true;
                        break;
                    }
                }
                //flag  == true 说明答对了

            }
        }

        return null;
    }
}
